<script setup lang="ts" name="TrackPlayback">
// import dayjs from 'dayjs';
import { vehicleTrajectoryMapKey } from './provider';

// const date = defineModel<string[]>('date', { required: true });

const props = defineProps<{
	pathData: Array<{
		lng: number;
		lat: number;
		time: string;
	}>;
}>();

enum PlayState {
	Init = 0,
	Play = 1,
	Pause = 2,
	RESUME = 3,
}

// const emits = defineEmits<{
// 	'update:date': [data: string[]];
// 	dateChange: [data: string[]];
// }>();

// TODO 时间进度条与地图联动、播放速度联动
// 参考 https://segmentfault.com/a/1190000021776525

/**
 * 功能
 * 播放 暂停 继续播放 倍速播放
 * 进度条
 *  点击进度条与地图car marker联动
 */
const vehicleTrajectoryMapProvider = inject<{
	startCarMarkerAnimation: (speed: number, init?: boolean) => void;
	pauseCarMarkerAnimation: () => void;
	resumeCarMarkerAnimation: () => void;
	setCarMovingEvent: (
		cb: (
			e: any,
			data: {
				data: {
					lng: number;
					lat: number;
					time: string;
				};
				index: number;
			},
		) => void,
	) => void;
	setCarMovealongEvent: (cb: () => void) => void;
	setCarMarkerMoveCurrentPosition: (time: string) => void;
}>(vehicleTrajectoryMapKey);

// 计时器
let progressTimer: NodeJS.Timer | null = null;

// 开始进度条计时器
function startProgressTimer() {
	if (progressTimer) clearInterval(progressTimer);

	// 根据播放速度设置interval
	const interval = 1000 / (speedCount.value * 2); // 增加更新频率

	progressTimer = setInterval(() => {
		if (
			markerPlayStatus.value === PlayState.Play ||
			markerPlayStatus.value === PlayState.RESUME
		) {
			// 每次增加1秒的进度
			sliderValue.value += 0.5; // 减小每次增加的值，使动画更平滑

			// 检查是否到达终点
			if (sliderValue.value >= sliderMax.value) {
				stopProgressTimer();
				markerPlayStatus.value = PlayState.Init;
			}
		}
	}, interval);
}

// 停止进度条计时器
function stopProgressTimer() {
	if (progressTimer) {
		clearInterval(progressTimer);
		progressTimer = null;
	}
}

// 移动中
// 记录拖动silder的值

// vehicleTrajectoryMapProvider?.setCarMovingEvent(
// 	(
// 		e,
// 		data: {
// 			data: {
// 				lng: number;
// 				lat: number;
// 				time: string;
// 			};
// 			index: number;
// 		},
// 	) => {
// 		// console.log('moving', data.index, sliderValue.value);
// 	},
// );

// 移动结束
vehicleTrajectoryMapProvider?.setCarMovealongEvent(() => {
	markerPlayStatus.value = PlayState.Init;
	// 保持最后的进度条位置
});

const pointDuration = ref(1000); // 每个点1秒
const speedCount = ref(1);
const speedList = [1, 2, 4, 8];

// function dateChange(e: any) {
// 	sliderValue.value = 0;
// 	speedCount.value = 1;
// 	markerPlayClick(PlayState.Init);

// 	emits('dateChange', e);
// }
// 播放速度变更
function speedChange() {
	// 重新启动计时器以更新速度
	if (
		markerPlayStatus.value === PlayState.Play ||
		markerPlayStatus.value === PlayState.RESUME
	) {
		startProgressTimer();
		vehicleTrajectoryMapProvider?.startCarMarkerAnimation(
			pointDuration.value / speedCount.value,
			false,
		);
	}
	sliderValue.value = 0;
}

const sliderValueCopy = ref(0);
// 播放状态 0 未播放 1 播放 2 暂停
const markerPlayStatus = ref(PlayState.Init);
// 播放速度
function markerPlayClick(type: PlayState, isInit: boolean = true) {
	markerPlayStatus.value = type;
	console.log('markerPlayStatus', markerPlayStatus.value, PlayState.Play);

	if (type === PlayState.Play) {
		// 播放时启动计时器
		startProgressTimer();

		if (isInit || sliderValue.value === 0) {
			sliderValue.value = 0;
			// 从头开始播放
			console.log(pointDuration.value, speedCount.value, 99999999999);
			vehicleTrajectoryMapProvider?.startCarMarkerAnimation(
				pointDuration.value / speedCount.value,
				true,
			);
		} else {
			// 从当前位置继续播放
			console.log('444444444继续播放');
			const pathArr = props.pathData
				.slice(Math.floor((sliderValue.value * 1000) / pointDuration.value))
				.map((item) => ({
					position: [item.lng, item.lat],
					...item,
				}));

			vehicleTrajectoryMapProvider?.startCarMarkerAnimation(
				pointDuration.value / speedCount.value,
				false,
				pathArr,
			);
		}
	} else if (type === PlayState.RESUME) {
		// 继续播放时启动计时器
		console.log('444444444继续播放3333');
		startProgressTimer();
		// 从当前位置继续播放
		const pathArr = props.pathData
			.slice(Math.floor((sliderValue.value * 1000) / pointDuration.value))
			.map((item) => ({
				position: [item.lng, item.lat],
				...item,
			}));

		vehicleTrajectoryMapProvider?.startCarMarkerAnimation(
			pointDuration.value / speedCount.value,
			false,
			pathArr,
		);
	} else if (type === PlayState.Pause) {
		// 暂停时停止计时器
		stopProgressTimer();
		vehicleTrajectoryMapProvider?.pauseCarMarkerAnimation();
	}
}

// slider
const sliderValue = ref(0);
const sliderMax = computed(() => {
	// 总时长 = 轨迹点数 * 每段时长 / 1000
	return ((props.pathData?.length || 0) * pointDuration.value) / 1000;
});
function formatTooltip(value: number) {
	console.log(props.pathData, 44444);
	// 根据进度条值计算对应的轨迹点索引和时间
	if (props.pathData && props.pathData.length) {
		const index = Math.min(
			Math.floor((value * 1000) / pointDuration.value),
			props.pathData.length - 1,
		);

		return props.pathData[index].time;
	}
	return '';
}

function sliderChange(e: any) {
	console.log(e);
	markerPlayClick(PlayState.Pause);

	sliderValueCopy.value = e;
	sliderValue.value = e;

	// 根据进度条值计算对应的轨迹点索引
	const index = Math.min(
		Math.floor((e * 1000) / pointDuration.value),
		props.pathData.length - 1,
	);

	// 设置车辆位置
	vehicleTrajectoryMapProvider?.setCarMarkerMoveCurrentPosition(
		props.pathData[index].time,
	);
}

// function sliderInput() {
// 	// 暂停
// 	markerPlayClick(PlayState.Pause);
// }
function speedClick(val: any) {
	speedCount.value = val;
	speedChange();
}

onUnmounted(() => {
	stopProgressTimer();
});
</script>

<template>
	<div class="date-picker absolute bottom-4 px-3 py-2 flex flex-col">
		<!-- <el-date-picker
			v-model="date"
			type="datetimerange"
			range-separator="至"
			start-placeholder="开始时间"
			end-placeholder="结束时间"
			value-format="YYYY-MM-DD HH:mm:ss"
			@change="dateChange"
		/> -->
		<div class="date-top flex items-center">
			<p class="date-top-p"></p>
			<p class="date-top-txt ml-3">轨迹播放</p>
			<p class="date-top-txt2 ml-10">倍数播放</p>
			<div class="dateList">
				<span
					class="ml-3"
					:class="{ active: speed == speedCount }"
					v-for="speed in speedList"
					:key="speed"
					@click="speedClick(speed)"
				>
					{{ speed + 'x' }}
				</span>
			</div>
		</div>

		<div class="flex-1 flex items-center mt-2">
			<div
				v-show="markerPlayStatus === PlayState.Init"
				class="w-7 h-7 mr-3 rounded border border-[#ddd] shrink-0 flex items-center justify-center text-primary cursor-pointer"
				@click="markerPlayClick(PlayState.Play)"
			>
				<i class="fa fa-solid fa-play" />
			</div>
			<div
				v-show="
					markerPlayStatus === PlayState.Play ||
					markerPlayStatus === PlayState.RESUME
				"
				class="w-7 h-7 mr-3 rounded border border-[#ddd] shrink-0 flex items-center justify-center text-primary cursor-pointer"
				@click="markerPlayClick(PlayState.Pause)"
			>
				<i class="fa fa-solid fa-pause" />
			</div>

			<div
				v-show="markerPlayStatus === PlayState.Pause"
				class="w-7 h-7 mr-3 rounded border border-[#ddd] shrink-0 flex items-center justify-center text-primary cursor-pointer"
				@click="markerPlayClick(PlayState.RESUME)"
			>
				<i class="fa fa-solid fa-play" />
			</div>

			<el-slider
				v-model="sliderValue"
				:max="sliderMax"
				:format-tooltip="formatTooltip"
				@change="sliderChange"
			/>
			<!-- <el-select class="shrink-0 ml-3" v-model="speedCount" suffix-icon="" @change="speedChange">
				<el-option v-for="speed in speedList" :key="speed" :label="speed + 'x'" :value="speed" />
			</el-select> -->
		</div>
	</div>
</template>

<style lang="scss" scoped>
.date-picker {
	width: 410px;
	height: 88px;
	left: 2%;
	right: 23%;
	background: #ffffff;
	box-shadow: 0px 2px 14px 0px rgba(0, 0, 0, 0.08);
	border-radius: 10px;

	:deep(.el-date-editor.el-input__wrapper) {
		width: 319px;
		height: 28px;
		border-radius: 3px;
		border: 1px solid #dddddd;
		box-shadow: none;
		flex-grow: 0;
	}

	:deep(.el-slider) {
		--el-slider-button-wrapper-size: 32px;
		--el-slider-button-size: 12px;
		--el-slider-height: 2px;
	}

	:deep(.el-select) {
		width: 28px;
		height: 28px;

		.el-select__wrapper {
			padding: 0;
			height: inherit;
			min-height: auto;
		}

		.el-select__suffix {
			display: none;
		}

		.el-select__placeholder {
			text-align: center;
		}
	}
}
.date-top-p {
	width: 5px;
	height: 20px;
	background: #2596ff;
	border-radius: 3px;
}
.date-top-txt {
	font-family: Source Han Sans CN;
	font-weight: bold;
	font-size: 18px;
	color: #222222;
	line-height: 24px;
}
.date-top-txt2 {
	font-family: Source Han Sans CN;
	font-weight: 500;
	font-size: 14px;
	color: #999999;
	line-height: 24px;
}
.dateList span {
	font-family: Source Han Sans CN;
	font-weight: 500;
	font-size: 14px;
	color: #666666;
	line-height: 24px;
}
.dateList .active {
	font-family: Source Han Sans CN;
	font-weight: 500;
	font-size: 14px;
	color: #2596ff;
	line-height: 24px;
}
</style>
